package com.bruce.demo2.patterns.demo2.structural.demo06.proxy.demo2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @PROJECT_NAME design_patterns
 * @DESCRIPTION 代理工厂，用来创建代理对象
 * @AUTHOR CNBruceLee
 * @DATE 2021/7/15 6:45
 */
public class ProxyFactory {
    private TrainStation station = new TrainStation();

    public SellTickets getProxyObject() {

        SellTickets sellTickets = (SellTickets) Proxy.newProxyInstance(
                station.getClass().getClassLoader(),
                station.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     *
                     * @param proxy  代理对象
                     * @param method 对应于代理对象上调用接口的方法的method实例
                     * @param args 代理对象调用接口方法时传递的实际参数
                     * @return
                     * @throws Throwable
                     */
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("代理点收取一些服务费用(JDK动态代理方式)");
                        //执行目标对象的方法
                        Object retObj = method.invoke(station, args);
                        return retObj;
                    }
                }
        );

        return sellTickets;
    }
}
